package com.shy.configs.common.mail;

import com.shy.configs.common.mail.model.AttachFile;
import com.shy.configs.common.mail.model.MailProperties;
import jakarta.annotation.Resource;
import jakarta.mail.internet.MimeMessage;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MailClient {
    @Resource
    private JavaMailSender javaMailSender;

    //简单邮件发送
    public boolean sendSimpleMail(MailProperties mailProperties) {
        boolean send = false;
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            // 发件人
            message.setFrom(mailProperties.getFrom());
            // 收件人
            message.setTo(mailProperties.getTo());
            // 邮件主题
            message.setSubject(mailProperties.getSubject());
            // 邮件内容
            message.setText(mailProperties.getText());
            // 发送邮件
            javaMailSender.send(message);
            // 打印日志到控制台
            System.out.println("-------------Successfully sent-------------");
        } catch (Exception e) {
            System.err.println("-------------Fail in send：" + e.getMessage() + "-------------");
        }
        return send;
    }

    //附件邮件发送
    public boolean sendAttachmentsMail(MailProperties mailProperties) {
        boolean send = false;
        try {
            //邮件主题
            MimeMessage message = javaMailSender.createMimeMessage();
            //给邮件设置属性
            //multipart：表示邮件内容中包含附件
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            // 发件人
            helper.setFrom(mailProperties.getFrom());
            // 收件人
            helper.setTo(mailProperties.getTo());
            // 邮件主题
            helper.setSubject(mailProperties.getSubject());
            // 邮件内容
            helper.setText(mailProperties.getText());
            // 附件
            List<AttachFile> attachFiles = mailProperties.getAttachFiles();
            if (attachFiles != null) {
                for (AttachFile attachFile : attachFiles) {
                    helper.addAttachment(attachFile.getName(), attachFile.getFile());
                }
            }
            // 发送邮件
            javaMailSender.send(helper.getMimeMessage());
            send = true;
            // 打印日志到控制台
            System.out.println("Successfully sent！！！");
        } catch (Exception e) {
            System.err.println("Fail in send：" + e.getMessage());
        }
        return send;
    }
}

